const { regClass, property } = Laya;

@regClass()
export class PlayerControllerV2 extends Laya.Script {
    @property(Number)
    // 移动速度（米/秒）
    public moveSpeed: number = 5;
    @property(Number)
    // 旋转速度（度/秒）
    public rotateSpeed: number = 180;

    private _rigidbody: Laya.Rigidbody3D;
    private _transform: Laya.Transform3D;
    private _keyStates: { [key: number]: boolean } = {};
    @property(Laya.Animator)
    private _animator: Laya.Animator;

    @property(Laya.CharacterController)
    private character: Laya.CharacterController

    onStart(): void {
        this._transform = (this.owner as Laya.Sprite3D).transform;
        this._rigidbody = this.owner.getComponent(Laya.Rigidbody3D);

        this._animator = this.owner.getComponent(Laya.Animator);

        this.character = this.owner.getComponent(Laya.CharacterController) as Laya.CharacterController;
    }

    public onBegin(): void {

    }

    public onMove(curdis: any, angle: any): void {
        this.apply(curdis, angle);
    }

    public onEnd(): void {
        this.apply(0,0)
    }


    apply(horizontal: any, vertical: any): void {
        if(this._transform==null) return
        var deltaTime = Laya.timer.delta / 1000;
        // 计算移动方向（基于当前朝向）
        const moveDirection = new Laya.Vector3();
       // console.log(this._transform)
        this._transform.getForward(moveDirection);
        moveDirection.y = 0; // Ensure movement is only on the XZ plane
        Laya.Vector3.normalize(moveDirection, moveDirection);
        Laya.Vector3.scale(moveDirection, -vertical * this.moveSpeed * deltaTime, moveDirection);

        // 计算旋转量
        const rotation = this._transform.localRotationEuler;
        rotation.y -= horizontal * this.rotateSpeed * deltaTime;

        // 应用运动
        this.applyMove(moveDirection, rotation);

        // 播放动画
        if (vertical !== 0 || horizontal !== 0) {
            this._animator.play("Run_loop");
        } else {
            this._animator.play("Idle_loop");
        }
        //jump
        Laya.InputManager.hasKeyDown(69) && this.character.jump()
    }


    applyMove(moveDirection: any, rotation: any): void {
        if (this.character) {
            this.character.move(moveDirection)
            this._transform.localRotationEuler = rotation;
        }
        else if (this._rigidbody) {
            this._rigidbody.linearVelocity = moveDirection;
            this._transform.localRotationEuler = rotation;
        } else {
            this._transform.translate(moveDirection, false);
            this._transform.localRotationEuler = rotation;
        }
    }
}